#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
浏览器设置脚本 - 帮助用户手动设置浏览器路径
"""

import os
import sys
import json
from pathlib import Path
import tkinter as tk
from tkinter import filedialog, messagebox

def get_default_browser_paths():
    """获取默认浏览器路径"""
    default_paths = []
    
    # Windows系统常见浏览器路径
    if sys.platform == 'win32':
        paths = [
            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
            r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
            r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
        ]
        for path in paths:
            if os.path.exists(path):
                default_paths.append(path)
    
    # macOS系统常见浏览器路径
    elif sys.platform == 'darwin':
        paths = [
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
        ]
        for path in paths:
            if os.path.exists(path):
                default_paths.append(path)
    
    # Linux系统常见浏览器路径
    else:
        paths = [
            "/usr/bin/google-chrome",
            "/usr/bin/chromium-browser",
            "/usr/bin/chromium",
            "/usr/bin/microsoft-edge"
        ]
        for path in paths:
            if os.path.exists(path):
                default_paths.append(path)
    
    return default_paths

def save_browser_config(browser_path):
    """保存浏览器配置"""
    # DrissionPage 4.0.0b3配置文件路径
    config_dir = Path.home() / ".DrissionPage"
    config_path = config_dir / "chrome_options.json"
    
    # 确保配置目录存在
    config_dir.mkdir(exist_ok=True)
    
    # 读取现有配置（如果存在）
    config = {}
    if config_path.exists():
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
        except Exception as e:
            print(f"读取配置文件失败: {e}")
    
    # 更新浏览器路径
    config['browser_path'] = browser_path
    
    # 保存配置
    try:
        with open(config_path, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=4)
        print(f"浏览器路径已保存到: {config_path}")
        return True
    except Exception as e:
        print(f"保存配置文件失败: {e}")
        return False

def create_gui():
    """创建图形界面"""
    root = tk.Tk()
    root.title("小红书爬虫 - 浏览器设置")
    root.geometry("600x400")
    
    # 获取默认浏览器路径
    default_paths = get_default_browser_paths()
    
    # 创建标签
    tk.Label(root, text="小红书爬虫 - 浏览器设置", font=("Arial", 16)).pack(pady=20)
    tk.Label(root, text="请选择Chrome或Edge浏览器可执行文件路径:").pack(pady=10)
    
    # 创建浏览器路径输入框和浏览按钮
    frame = tk.Frame(root)
    frame.pack(fill=tk.X, padx=20, pady=10)
    
    path_var = tk.StringVar()
    if default_paths:
        path_var.set(default_paths[0])
    
    path_entry = tk.Entry(frame, textvariable=path_var, width=50)
    path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
    
    def browse_file():
        filepath = filedialog.askopenfilename(
            title="选择浏览器可执行文件",
            filetypes=[
                ("可执行文件", "*.exe") if sys.platform == 'win32' else ("所有文件", "*.*")
            ]
        )
        if filepath:
            path_var.set(filepath)
    
    browse_button = tk.Button(frame, text="浏览...", command=browse_file)
    browse_button.pack(side=tk.RIGHT)
    
    # 显示检测到的浏览器
    if default_paths:
        tk.Label(root, text="系统检测到的浏览器:").pack(anchor=tk.W, padx=20, pady=(20, 5))
        browser_frame = tk.Frame(root)
        browser_frame.pack(fill=tk.X, padx=20)
        
        for i, path in enumerate(default_paths):
            def select_path(p=path):
                path_var.set(p)
            
            browser_name = "Chrome" if "chrome" in path.lower() else "Edge" if "edge" in path.lower() else "未知浏览器"
            button = tk.Button(browser_frame, text=f"选择 {browser_name}", command=select_path)
            button.grid(row=i//2, column=i%2, padx=5, pady=5, sticky=tk.W)
            tk.Label(browser_frame, text=path, wraplength=450).grid(row=i//2, column=i%2+2, padx=5, pady=5, sticky=tk.W)
    else:
        tk.Label(root, text="未检测到系统浏览器，请手动选择浏览器路径").pack(pady=20)
    
    # 保存按钮
    def save_config():
        browser_path = path_var.get()
        if not browser_path:
            messagebox.showerror("错误", "请选择浏览器路径")
            return
        
        if not os.path.exists(browser_path):
            messagebox.showerror("错误", "选择的浏览器路径不存在")
            return
        
        if save_browser_config(browser_path):
            messagebox.showinfo("成功", "浏览器路径已保存！\n现在可以启动爬虫程序了。")
            root.destroy()
        else:
            messagebox.showerror("错误", "保存配置失败")
    
    save_button = tk.Button(root, text="保存配置", font=("Arial", 12), command=save_config, bg="#4CAF50", fg="white")
    save_button.pack(pady=30)
    
    # 启动GUI主循环
    root.mainloop()

def main():
    """主函数"""
    print("=== 小红书爬虫 - 浏览器设置工具 ===\n")
    
    # 检查是否已安装DrissionPage
    try:
        import DrissionPage
        print(f"已安装DrissionPage版本: {DrissionPage.__version__}")
    except ImportError:
        print("未安装DrissionPage，请先运行: pip install DrissionPage==4.0.0b3")
        return
    
    # 获取默认浏览器路径
    default_paths = get_default_browser_paths()
    if default_paths:
        print("检测到系统浏览器:")
        for i, path in enumerate(default_paths):
            print(f"{i+1}. {path}")
    else:
        print("未检测到系统浏览器")
    
    # 命令行模式
    if len(sys.argv) > 1:
        if sys.argv[1] == "--cli":
            # CLI模式
            if default_paths:
                browser_path = default_paths[0]
                print(f"\n将使用默认浏览器: {browser_path}")
                if save_browser_config(browser_path):
                    print("浏览器路径已保存！现在可以启动爬虫程序了。")
                else:
                    print("保存配置失败")
            else:
                print("\n未检测到浏览器，请手动运行并选择浏览器路径")
            return
        elif os.path.exists(sys.argv[1]):
            # 使用命令行提供的路径
            browser_path = sys.argv[1]
            print(f"\n将使用指定浏览器: {browser_path}")
            if save_browser_config(browser_path):
                print("浏览器路径已保存！现在可以启动爬虫程序了。")
            else:
                print("保存配置失败")
            return
    
    # 显示GUI
    try:
        create_gui()
    except Exception as e:
        print(f"启动GUI失败: {e}")
        print("\n请手动设置浏览器路径:")
        
        if default_paths:
            for i, path in enumerate(default_paths):
                print(f"{i+1}. {path}")
            
            try:
                choice = int(input("\n请输入选择的序号 (1-{0}): ".format(len(default_paths))))
                if 1 <= choice <= len(default_paths):
                    browser_path = default_paths[choice-1]
                    if save_browser_config(browser_path):
                        print("浏览器路径已保存！现在可以启动爬虫程序了。")
                    else:
                        print("保存配置失败")
                else:
                    print("无效的选择")
            except ValueError:
                print("请输入有效的数字")
        else:
            print("未检测到浏览器，请手动指定浏览器路径")

if __name__ == "__main__":
    main() 